import Request, { HttpRequestConfig } from 'luch-request';
import { assign } from 'lodash-es';
import { showToast } from '@/utils/prompt';
import { getBaseUrl } from '@/utils/env';
import { useUserStore } from '@/store/user';
import { ResultEnum } from '@/enums/httpEnum';
import { loginWhitelist } from '@/utils/constant';
import { gotoLogin } from '@/utils/permission';
import { redirectNameTo } from '@/utils/utils';
import { redirectTo } from '@/utils/utils';
import {createTransformComponentLink} from "@dcloudio/uni-cli-shared";


const BASE_URL = getBaseUrl();
console.log(' BASE_URL--', BASE_URL);
const HEADER = {
  'Content-Type': 'application/json;charset=UTF-8;',
  Accept: 'application/json, text/plain, */*'
};

function createRequest() {
  return new Request({
    baseURL: BASE_URL,
    header: HEADER,
    custom: {
      auth: true
    }
  });
}

let needLogin = false;

const request = createRequest();

/**
 * 请求拦截器
 */
request.interceptors.request.use(
  (options: any) => {
    needLogin = false;
    const userStore = useUserStore();
    // 需要登录，并且不属于登录白名单
      let url = options.url.split('?')[0];
      if (!userStore.isLogin && !loginWhitelist.includes(url as string)) {
      showToast('请先登录');
      gotoLogin(); // token不存在跳转到登录页
      needLogin = true;
      return Promise.reject(options);
    }
    assign(options.header, {
      authorization: userStore.getToken() ?? ''
    });
    return options;
  },
  (options: any) => Promise.reject(options)
);

/**
 * 响应拦截器
 */
request.interceptors.response.use(

async (response: any) => {
    const { header, statusCode, errMsg, data, config } = response;
      if ( data.code == 401) {
          showToast('请先登录');
          gotoLogin(); // token不存在跳转到登录页
          return Promise.reject(response);
      }else if (data.code == 500) {
          showToast('系统操作失败,请联系管理员');
          return Promise.reject(response);
      }else {
          return Promise.resolve(response);
      }
  },
  (response: any) => {
    if (needLogin || (response.data && response.data.code && response.data.code == 401)) {
        const userStore = useUserStore();
        userStore.setToken('');
        showToast('请先登录');
        gotoLogin(); // token不存在跳转到登录页
    } else if (response.data.code === 403) {
        redirectNameTo('promptPage', { errMsg: response.errMsg });
    }  else if (response.data.code == 500){
        return Promise.resolve(response);
        // 部分错误返回可能无data.errorMsg但有data.error，都没有则默认提示
        const errorMsg = response?.data?.msg || response?.data?.error || '接口异常';
        showToast(errorMsg)
    }
    return Promise.reject(response);
  }
);

// 对请求再次封装
const http = {
  async get<T>(
    url: string,
    config?: HttpRequestConfig<UniApp.RequestTask> | undefined
  ) {
    const res = await request.get<T>(url, config);
    return res.data;
  },
  async post<T>(
    url: string,
    data?: AnyObject | undefined,
    config?: HttpRequestConfig<UniApp.RequestTask> | undefined
  ) {
    const res = await request.post<T>(url, data, config);
    return res.data;
  },
  async put<T>(
    url: string,
    data?: AnyObject | undefined,
    config?: HttpRequestConfig<UniApp.RequestTask> | undefined
  ) {
    const res = await request.put<T>(url, data, config);
    return res.data;
  },
  async delete<T>(
    url: string,
    data?: AnyObject | undefined,
    config?: HttpRequestConfig<UniApp.RequestTask> | undefined
  ) {
    const res = await request.delete<T>(url, data, config);
    return res.data;
  }
};
export { request, http };
